package com.padakeji.android.pworks.module.image.view;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.padakeji.android.pworks.R;

import java.util.ArrayList;

/**
 * Created by AtanL on 2015/9/20.
 */
public class ImageViewerFragment extends Fragment {

    public interface OnImageChangeListener {
        void onImageSelected(int position);
    }

    private boolean mCalled = false;

    private ImagePagerAdapter imagePagerAdapter;

    private ViewPager imagesPager;
    private OnImageChangeListener onImageChangeListener;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        imagePagerAdapter = new ImagePagerAdapter(getActivity());

        mCalled = true;
    }

    public void setArguments(ArrayList<String> imagePaths, int currentItemIndex) {
        if (!mCalled) {
            throw new RuntimeException("setArguments(ArrayList<String>, int) must be called after ImageViewerFragment created.");
        }
        if (imagePaths == null) {
            imagePaths = new ArrayList<>();
        }
        imagePagerAdapter.setImagePaths(imagePaths);
        imagePagerAdapter.notifyDataSetChanged();
        if (currentItemIndex >= 0 && currentItemIndex < imagePaths.size()) {
            imagesPager.setCurrentItem(currentItemIndex);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.pworks_fragment_image_viewer, container, false);
        imagesPager = (ViewPager) v.findViewById(R.id.pworks_fragment_image_viewer_pager_images);
        imagesPager.setOnPageChangeListener(new MyOnPageChangeListener());
        imagesPager.setAdapter(imagePagerAdapter);
        return v;
    }

    public void setOnImageChangeListener(OnImageChangeListener onImageChangeListener) {
        this.onImageChangeListener = onImageChangeListener;
    }

    public int getCurrentItemIndex() {
        return imagesPager.getCurrentItem();
    }

    private class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            if (onImageChangeListener != null) {
                onImageChangeListener.onImageSelected(position);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

}
